package api

import (
	"certificate-manager/pkg/app"
	"certificate-manager/pkg/e"
	"certificate-manager/pkg/log"
	"certificate-manager/pkg/utils"
	"certificate-manager/thirdparty/acmee"
	"certificate-manager/thirdparty/redisc"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
)

// ValidateAccount 校验letsencrypt账号有效性
func ValidateAccount(c *gin.Context) {
	appG := app.Gin{C: c}

	//1、获取letsencrypt账号信息
	rdb, err := redisc.GetRedisClientInstance()
	if err != nil {
		log.Logger.Error("【ValidateAccount】failed create new redis client.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.RedisError, nil)
		return
	}

	//2、从redis中获取Let's encrypt Account（默认CA）
	account, err := rdb.FetchLetencryptAccount()
	if err != nil {
		log.Logger.Error("【ValidateAccount】failed to get lets-encrypt Account from redis.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.GetLetsEncryptAccountError, nil)
		return
	}

	//3、账号信息不存在
	if account == nil {
		log.Logger.Info("【ValidateAccount】no let's encrypt Account exists in redis.")

		//4、创建账号
		err := acmee.CreateLetsencryptAccount(rdb)
		if err != nil {
			log.Logger.Error("【ValidateAccount】failed create let's encrypt Account.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
			appG.Response(http.StatusOK, e.GetLetsEncryptAccountError, nil)
		}

		log.Logger.Info("【ValidateAccount】create let's encrypt Account finish.")

		appG.Response(http.StatusOK, e.SUCCESS, nil)
		return
	}

	//4、账号信息已存在，判断状态是否有效
	log.Logger.Info("【ValidateAccount】start verify lets encrypt Account status.")
	err = acmee.CheckAccountStatus(account, rdb)
	if err != nil {
		// 5、账号信息检查失败
		log.Logger.Error("【ValidateAccount】Account status check error.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.CheckLetsEncryptAccountError, nil)
		return
	}

	//6、账号存在且有效
	log.Logger.Info("【ValidateAccount】let's encrypt Account is existed and status is valid.")
	appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
		"msg": "检查成功",
	})
}
